package com.fh.web.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.bo.PageFilterBo;
import com.fh.bo.PurRoleBo;
import com.fh.dto.PubDdv;
import com.fh.dto.PurRole;
import com.fh.dto.SysUser;
import com.fh.web.constants.FhManagerConstant;
import com.fh.web.constants.GlobalConstants;
import com.fh.web.service.CustomService;
import com.fh.web.service.PurRoleService;
import com.fh.web.service.PurviewService;
import com.fh.web.vo.PurRoleVo;
import com.fh.web.vo.PurviewVo;
import com.fh.web.vo.ShowGridVo;
import com.fh.web.vo.ShowTreeVo;

/**
 * 角色管理controller
 * 
 * @author admin
 *
 */
@Controller
@RequestMapping(value = "role")
public class PurRoleController {
	// 打印logger日志
	private final Logger LOGGER = LoggerFactory.getLogger(getClass());

	@Resource
	private CustomService customService;

	@Resource
	private PurRoleService purRoleService;

	@Resource
	private PurviewService purviewService;

	/**
	 * 跳转角色管理页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/manager", method = { RequestMethod.GET, RequestMethod.POST })
	private ModelAndView manager(HttpServletRequest request) {
		// 申明返回页面参数map
		Map<String, Object> resMap = new HashMap<String, Object>();
		String pId = request.getParameter("id");
		try {
			// 从session获取用户信息
			SysUser staff = (SysUser) SecurityUtils.getSubject().getSession().getAttribute(GlobalConstants.SYS_USER);
			if (staff != null) {
				// 判断用户操作权限
				resMap = customService.userCanOperation(staff, pId);
				resMap.put("resCode", FhManagerConstant.RST_SUCCESS);
			} else {
				resMap.put("resCode", FhManagerConstant.RST_FAIL);
			}
		} catch (Exception e) {
			resMap.put("resCode", FhManagerConstant.RST_FAIL);
			LOGGER.error("跳转角色管理页面异常", e);
		}
		return new ModelAndView("role/role", resMap);
	}

	/**
	 * 查询所有角色
	 * 
	 * @param ph
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/roleListData", method = { RequestMethod.GET, RequestMethod.POST })
	private ShowGridVo userListData(PageFilterBo ph, HttpServletRequest request) {
		// 申明easyUi前台封装数据
		ShowGridVo gridBo = new ShowGridVo();
		try {
			// 分页查询权限
			Map<String, Object> map = purRoleService.selectAllRole(ph);
			List<PurRoleBo> roleList = (List<PurRoleBo>) map.get("list");
			Long toltal = (Long) map.get("pageTatal");
			// 设置前台分页参数
			gridBo.setRows(roleList);
			gridBo.setTotal(toltal.intValue());

		} catch (Exception e) {
			LOGGER.error("获取所有角色异常", e);
			return null;
		}
		return gridBo;
	}

	/**
	 * 查询角色信息
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/editPage", method = { RequestMethod.GET, RequestMethod.POST })
	private ModelAndView editPage(Long id, HttpServletRequest request) {

		try {
			// 根据id查询角色
			PurRoleVo roleDto = purRoleService.selectRoleById(id);
			request.setAttribute("roleDto", roleDto);
		} catch (Exception e) {
			LOGGER.error("获取角色信息异常", e);
		}
		return new ModelAndView("role/roleEdit");
	}

	@RequestMapping(value = "/addRole", method = { RequestMethod.GET, RequestMethod.POST })
	private ModelAndView addRole(Integer id, HttpServletRequest request) {
		return new ModelAndView("role/roleAdd");
	}

	/**
	 * 添加角色 
	 * 
	 * @param roleDto
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/addRoleJson", method = { RequestMethod.GET, RequestMethod.POST })
	private PurRole addRoleJson(PurRoleVo purRoleVo, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		PurRoleVo role = new PurRoleVo();
		try {
			// session获取用户登录信息
			SysUser user = (SysUser) request.getSession().getAttribute(GlobalConstants.SYS_USER);
			if (user == null) {
				// 用户未登陆，放回状态-1
				role.setState(-1);
				return role;
			} else {
				// 添加角色
				if (0 == purRoleService.checkRole(purRoleVo)) {
					purRoleService.addRole(purRoleVo, user.getUserId().intValue());
					// 成功返回状态0
					role.setState(0);
					return role;
				} else {
					// 失败返回状态1
					role.setState(2);
					return role;
				}

			}
		} catch (Exception e) {
			LOGGER.error("添加角色信息异常", e);
			// 错误返回1
			role.setState(1);
			return role;
		}
	}

	/**
	 * 修改角色信息
	 * 
	 * @param roleDto
	 * @return
	 * @throws Exception
	 *             
	 */
	@ResponseBody
	@RequestMapping(value = "/updateRole", method = { RequestMethod.GET, RequestMethod.POST })
	private PurRole updateRole(PurRoleVo purRoleVo, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		PurRoleVo role = new PurRoleVo();
		try {
			SysUser sysStaff = (SysUser) request.getSession().getAttribute(GlobalConstants.SYS_USER);
			if (sysStaff == null) {
				// 用户未登陆，放回状态-1
				role.setState(-1);
				return role;
			} else {
				// 更新角色信息
				if (0 == purRoleService.checkRole(purRoleVo)) {
					purRoleService.updateRole(purRoleVo);
					// 成功返回状态0
					role.setState(0);
					return role;
				} else {
					role.setState(2);
					return role;
				}
			}
		} catch (Exception e) {
			LOGGER.error("修改角色信息异常", e);
			role.setState(1);
			return role;
		}
	}

	/**
	 * 删除角色 
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteRole", method = { RequestMethod.GET, RequestMethod.POST })
	private PurRole deleteRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PurRoleVo roleDto = new PurRoleVo();
		String id = request.getParameter("id");
		try {
			Long roleId = Long.parseLong(id);
			// 检查角色下是否存在用户
			if (purRoleService.isExistUser(roleId)) {
				roleDto.setState(-1);
				return roleDto;
			}
			// 根据id删除角色
			purRoleService.deleteRoleById(roleId);
			// 查询是否删除成功
			PurRoleVo role = purRoleService.selectRoleById(Long.parseLong(id));
			if (role == null) {
				// 删除成功返回状态0
				roleDto.setState(0);
				return roleDto;
			} else {
				// 删除失败返回状态1
				roleDto.setState(1);
				return roleDto;
			}

		} catch (Exception e) {
			// 异常返回状态-1
			LOGGER.error("删除角色异常", e);
			roleDto.setState(-1);
			return roleDto;

		}
	}

	/**
	 * 获取角色下的所有权限点
	 * 
	 * @param request
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getRolePurview", method = { RequestMethod.GET, RequestMethod.POST })
	public List<PurviewVo> getRolePurview(Long rId) {
		// 申明权限点List
		List<PurviewVo> purDtoList = new ArrayList<PurviewVo>();
		try {
			// 根据角色查询所有权限点
			purDtoList = purviewService.getPurviewList(rId);
		} catch (Exception e) {
			LOGGER.error("获取角色下的所有权限点异常", e);
			return null;
		}
		return purDtoList;
	}

	/**
	 * 弹出授权页面
	 * 
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/grantPage", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView grantPage(Long rId) {
		// 申明返回参数map
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("rId", rId);
		return new ModelAndView("role/roleGrant", resMap);
	}

	/**
	 * 角色授权 
	 * 
	 * @param request
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/grant", method = { RequestMethod.GET, RequestMethod.POST })
	public void grant(Long rId, String[] purIds, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 申明easyUi返回参数
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();// 获取输出
		try {
			// session获取用户信息
			SysUser sysStaff = (SysUser) request.getSession().getAttribute(GlobalConstants.SYS_USER);
			// 角色授权
			purviewService.addGrant(rId, purIds, sysStaff);
			out.print("授权成功");
		} catch (Exception e) {
			out.print("授权失败");
			LOGGER.error("角色授权异常", e);
		}
	}

	/**
	 * 查询所有角色
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectAllRoles", method = { RequestMethod.GET, RequestMethod.POST })
	private List<ShowTreeVo> selectAllRoles() {
		// 申明easyUI返回tree实例
		List<ShowTreeVo> lt = new ArrayList<ShowTreeVo>();
		try {
			// 查询所有角色
			List<PurRoleVo> roleDtoList = purRoleService.selectRoles();
			if ((roleDtoList != null) && (roleDtoList.size() > 0)) {
				for (PurRoleVo r : roleDtoList) {
					// 申明tree节点实例
					ShowTreeVo tree = new ShowTreeVo();
					// 设置节点tree参数
					tree.setId(r.getRoId().toString());
					tree.setText(r.getToName());
					lt.add(tree);
				}
			}
		} catch (Exception e) {
			LOGGER.error("获取所有角色", e);
			return null;
		}
		return lt;
	}

	/**
	 * 查询所有角色类型
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getRoleType", method = { RequestMethod.GET, RequestMethod.POST })
	private List<PubDdv> getRoleType() {
		List<PubDdv> list = purRoleService.getRoleType();
		return list;
	}

}
